<template>
  <div class="category">
    <h1>{{id?'编辑':"新增"}}分类</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="所属分类:">
        <el-select v-model="form.parent">
          <el-option v-for="item in parents" :key="item._id" :label="item.name" :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称:">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import http from "../axios/index.js";
export default {
  props: {
    id: String,
  },
  data() {
    return {
      form: {},
      parents: [],
    };
  },
  created() {
    this.id && this.fetch();
    this.fetchParent();
  },
  methods: {
    // 获取
    async fetch() {
      const res = await this.$http.get(`/rest/categories/${this.id}`);
      this.form = res.data;
    },
    async fetchParent() {
      const res = await this.$http.get(`/rest/categories`);
      this.parents = res.data;
    },
    async save() {
      let res;
      if (this.id) {
        res = await this.$http.put(`/rest/categories/${this.id}`, this.form);
      } else {
        res = await this.$http.post("/rest/categories", this.form);
      }
      const { data } = res;
      if (data.code == 200) {
        this.$message.success(data.msg);
        this.$router.push("/categories/list");
      }
    },
  },
};
</script>

<style></style>
